package Application;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.PrintWriter;
import java.io.Serializable;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.SocketException;
import java.util.Random;
import java.util.Scanner;

import Networking.INetworkClient;
import Networking.NetworkHandler;

public class Client implements Runnable, Serializable, INetworkClient {

	private ObjectInputStream objectIn;
	private NetworkHandler networkHandler;
	private WorkUnit currentUnit;

	private static Random rand = new Random();

	private int ID;

	// TODO [Client] Add code to read ID from file

	public static void main(String[] args) {
		new Thread(new Client()).start();
	}

	public Client() {
		networkHandler = new NetworkHandler(ID, this);

		System.out.println("Client Starting");
		new Thread(new Runnable() {
			public void run() {
				try {

					// ID = rand.nextInt();

//					System.out.println("IN CLIENT(ID): " + ID);

				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}).start();

	}

	@Override
	public void run() {
		new Scanner(System.in).nextLine();
		// try {
		// socket.close();
		// } catch (IOException e) {
		// e.printStackTrace();
		// }
		System.out.println("Goodbye!");
		System.exit(0);
	}

	public WorkUnit getCurrentUnit() {
		return currentUnit;
	}

	public int getID() {
		return ID;
	}
	
	public void setID(int ID) {
		this.ID = ID;
		System.out.println("IN CLIENT(ID): " + ID);
	}

	@Override
	public void gotWorkUnit(WorkUnit workUnit) {
		currentUnit = workUnit;

		System.out.println("[Client:" + ID + "]Got work unit with ID: "
				+ currentUnit.getId());

		Thread t = new Thread(workUnit);
		t.start();
		while (t.isAlive())
			;

		for (Object obj : workUnit.getOutputs()) {
			int i = (Integer) obj;
			workUnit.getOutputs();
//			System.out.println("[Client:" + ID + "] Output: " + i);
		}
		
		System.out.println("Handled " + workUnit.getInputs().size() + " inputs");
		System.out.println("Handled " + workUnit.getOutputs().size() + " outputs");
		
		networkHandler.sendFinishedWorkUnit(workUnit);
	}

	public void closeConnection() throws SocketException {
		networkHandler.closeConnection();
	}

	public void testCloseSocket() {
		networkHandler.testCloseSocket();
	}
}
